package compiler;

import java.util.HashMap;
import java.util.Map;

public class VariableManager {

	private Map<String, Integer> variables;
	private Map< String, Type> types;
	private int nextFreeSpace = 0;
	private int maxFreeSpace;
	
	public VariableManager( int maxFreeSpace ){
		variables = new HashMap<String, Integer>();
		types = new HashMap<String, Type>();
		this.maxFreeSpace = maxFreeSpace;
	}
	public boolean isSetVariable( String name ){
		return variables.containsKey( name );
	}
	
	
	
	public boolean declareVariable( String name, Type type ){
		if ( isSetVariable(name) || type == Type.ERROR_TYPE_t ) return false;
		if ( maxFreeSpace < nextFreeSpace ) return false;
		variables.put( name , nextFreeSpace );
		types.put( name, type );
		nextFreeSpace += TypeManager.getTypeSize(type);
		
		return true;
	}
	
	public boolean declareVariableByString( String name, String type ){
		Type t = TypeManager.parseType(type);		
		declareVariable(name, t);
		System.out.println( "Defined new variable " + name + " / " + type + " with address " + getVariableAddress(name) );
		return true;
	}	
	
	public Type getVariableType( String name ){
		if ( this.isSetVariable(name) )	return types.get(name);
		System.out.println("Neexistujci promenna " + name);
		return Type.ERROR_TYPE_t;
	}
	
	public int getVariableAddress( String name ){
		if ( this.isSetVariable(name) ) return variables.get(name);
		System.out.println("Neexistujci promenna " + name);
		return -1;
	}
	

}
